package concurrecy;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class LockHolder {
    private Lock lock = new ReentrantLock();
    public LockHolder() {
        lock.lock();
    }

    public void f() {
        System.out.println("f invoked");
        try {
            lock.lockInterruptibly();
            try {
                // do something
            } finally {
                lock.unlock();
            }
        } catch (InterruptedException e) {
            System.out.println("Lock Interrupted");
        }
        System.out.println("f exited");
    }
}

class LockInterrupter implements Runnable {

    private LockHolder lockHolder;

    public LockInterrupter(LockHolder lockHolder) {
        this.lockHolder = new LockHolder();
    }

    @Override
    public void run() {
        lockHolder.f();
    }
}

/**
 * 锁中断
 */
public class LockInterruptDemo {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new LockInterrupter(new LockHolder()));
        thread.start();

        TimeUnit.SECONDS.sleep(2);
        System.out.println("thread.interrupt();");
        thread.interrupt();
    }
}
